#define _GNU_SOURCE
#include "app_device.h"
#include "app_ble.h"
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

Device_t *device = NULL;

int App_pool_SendToUp(void *args)
{
    char UpData_buf[128] = {0};
    int UpData_len = App_Buffer_Read(device->Up_Buffer, UpData_buf, 128);
    if (UpData_len == -1)
    {
        log_error("read from Upbuffer error");
        return -1;
    }
    char *UpData_json = app_message_charsToJson(UpData_buf, UpData_len);
    if (app_mqtt_send(UpData_json) == -1)
    {
        log_error("send to mqtt error");
        return -1;
    }
}

int App_pool_SendToDown(void *args)
{
    char DownData_buf[128] = {0};
    int DownData_len = App_Buffer_Read(device->Down_Buffer, DownData_buf, 128);
    log_debug("下行缓冲区的数据:%s 长度：%d", DownData_buf, DownData_len);
    if (DownData_len == -1)
    {
        log_error("read from Downbuffer error");
        return -1;
    }
    if (DownData_len && device->pre_write)
    {
        DownData_len = device->pre_write(DownData_buf, DownData_len);
        log_debug("下行缓冲区处理后的数据:%.*s", DownData_len, DownData_buf);
        if(DownData_len == -1)
        {
            log_error("写前预处理失败");
            return -1;
        }
        long CurrentTime = App_Common_GetCurrentTime();
        if(CurrentTime - device->last_write_timems < device->interval_ms)
        {
            usleep((device->interval_ms - (CurrentTime - device->last_write_timems)) * 1000);
        }
        write(device->fd, DownData_buf, DownData_len);
        device->last_write_timems = App_Common_GetCurrentTime();
    }
    // 为了测试方便,不使用处理函数,实际应用中将注释下面(53-62)行代码
    // if (DownData_len > 0)
    // {
    //     long CurrentTime = App_Common_GetCurrentTime();
    //     if(CurrentTime - device->last_write_timems < device->interval_ms)
    //     {
    //         usleep((device->interval_ms - (CurrentTime - device->last_write_timems)) * 1000);
    //     }
    //     write(device->fd, DownData_buf, DownData_len);
    //     device->last_write_timems = App_Common_GetCurrentTime();
    // }
}

static void *App_thread_Read(void *arg)
{
    char data_buf[128] = {0};
    while (device->is_running)
    {
        ssize_t len = read(device->fd, data_buf, 128);
        if (len == -1)
        {
            log_error("read error");
            return NULL;
        }
        if (len > 0 && device->post_read)
        {
            len = device->post_read(data_buf, len);
            if (len == -1)
            {
                log_error("读后预处理失败");
                return NULL;
            }
            if(len > 0)
            {
                if (App_Buffer_Write(device->Up_Buffer, data_buf, len) == -1)
                {
                    log_error("write UPBuffer error");
                    return NULL;
                }
                App_Pool_RegisterTask(App_pool_SendToUp, NULL);
            }
        }
        // 为了测试方便,不使用处理函数,实际应用中将注释下面(68-76)行代码
        // if (len > 0)
        // {
        //     if (App_Buffer_Write(device->Up_Buffer, data_buf, len) == -1)
        //     {
        //         log_error("write UPBuffer error");
        //         return NULL;
        //     }
        //     App_Pool_RegisterTask(App_pool_SendToUp, NULL);
        // }
    }
}

static int App_mqtt_RecvCallback(char *json)
{
    char chars_buf[128] = {0};
    log_debug("收到mqtt消息:%.*s", strlen(json), json);
    int chars_len = app_message_jsonToChars(json, chars_buf, 128);
    App_Buffer_Write(device->Down_Buffer, chars_buf, chars_len);
    App_Pool_RegisterTask(App_pool_SendToDown, NULL);
}

Device_t *App_Device_Init(char *filename)
{
    device = malloc(sizeof(Device_t));
    device->filename = filename;
    device->fd = open(filename, O_RDWR);
    device->Up_Buffer = App_Buffer_Init(1024);
    device->Down_Buffer = App_Buffer_Init(1024);
    device->is_running = 0;
    device->last_write_timems = 0;
    device->interval_ms = 200;
    device->post_read = NULL;
    device->pre_write = NULL;
    // 在进程中已经初始化了mqtt,此处不再初始化,直接使用即可
    // if(app_mqtt_init() == -1)
    // {
    //     log_error("mqtt初始化失败");
    //     return -1;
    // }
    // log_debug("mqtt初始化成功");
    return device;
}

void App_Device_Start(void)
{
    if (device->is_running)
    {
        log_debug("设备已经启动");
        return;
    }
    // if (App_Pool_Init(10) == -1)
    // {
    //     log_error("创建线程池失败");
    //     return;
    // }
    // log_debug("创建线程池成功");
    // App_BLE_Init(device);
    //log_debug("BLE初始化成功");
    pthread_create(&device->Read_Thread, NULL, App_thread_Read, NULL);
    device->is_running = 1;
    app_mqtt_registerRecvCallback(App_mqtt_RecvCallback);
}

void App_Device_Stop(void)
{
    App_Buffer_close(device->Down_Buffer);
    App_Buffer_close(device->Up_Buffer);
    //App_Pool_close();
    pthread_cancel(device->Read_Thread);
    pthread_join(device->Read_Thread, NULL);
    //app_mqtt_close();
    close(device->fd);
    free(device);
}
